import { isString, isFunction, isObject, isArray } from "lodash";

export default class PropsWatcher {
  constructor() {
    /**
     * {
     *  0: {
     *    myclick: [fn1, fn2, fn3]
     *  }
     * }
     */
    this.listenMap = {};
  }
  /**
   * 
   * @param {*} id 组件id
   * @param {*} key 事件名称
   * @param {*} fn 回调函数
   */
  on(compId, key, fn) {
    let compListener = this.listenMap[compId];
    // 事件名称必须是字符串，事件监听回调必须是函数
    if (isString(key) && isFunction(fn)) {
      if (!isObject(compListener)) {
        this.listenMap[compId] = {};
      }
      if (!isArray(this.listenMap[compId][key])) {
        this.listenMap[compId][key] = [];
      }
      this.listenMap[compId][key].push(fn);
    }
  }

  /**
   * 事件触发
   * @param {*} compId 组件id
   * @param {*} key 事件名称
   * @param {*} data 返回值
   */
  emit(compId, key, data) {
    let compListener = this.listenMap[compId];
    if (compId == 'all') {
      Object.keys(this.listenMap).forEach((cid) => {
        this.emit(cid, key, data);
      });
      return;
    } 
    if (isObject(compListener) && isArray(compListener[key]) && compListener[key].length > 0) {
      compListener[key].forEach(fn => {
        fn(data);
      });
    }
  }
}